import { App } from 'vue'
import storage from 'store'
import router from '@/router'
import { regAxios } from '../request/install'
import { message } from 'ant-design-vue'
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { mapState, useStore } from 'vuex'
//创建axios 示例

const request = axios.create({
    baseURL:import.meta.env.VITE_SERVER_REQUEST_BASE_URL as string,
    timeout: 6000
})

/**
 * @desc: 异常拦截处理器
 * @param {Object} error 错误信息 
 * @returns 
 */
const errorHandler = (error:AxiosError):AxiosError | Promise<AxiosError> => {
    message.error(error.message);
    return Promise.reject(error);
} 

request.interceptors.request.use((config:AxiosRequestConfig):AxiosRequestConfig =>{
    //let store=useStore();
    // const token=JSON.stringify(
    //     {
    //         Id :'8a010000-5d88-0015-e013-08d6bd87c815',
    //         FullName : "Test",
    //         Email : '763630473@qq.com',
    //         Phone : '18825195281',
    //         TenantId : '8a010000-5d88-0015-e013-08d6bd87c815'
    //     });
    //config.headers['Authorization'] ='Bearer '+encodeURIComponent(token);//storage.get('token') || '';
    config.headers['Authorization'] = storage.get('token') || '';
    return config;
},errorHandler)

request.interceptors.response.use((response:AxiosResponse):AxiosResponse | Promise<AxiosResponse> =>{
    if(response.data.Code==1){
        if(response.data.Data){
            if(response.data.Data.TotalCount !=undefined){
                response.data.total=response.data.Data.TotalCount;
            }
            if(response.data.Data.PageNo !=undefined){
                response.data.current=response.data.Data.PageNo;
            }
            if(response.data.Data.PageSize !=undefined){
                response.data.Size=response.data.Data.PageSize;
            }
            if(response.data.Data.List!=undefined){
                response.data.Data=response.data.Data.List;
            }
            if(response.data.Data.data!=undefined){
                response.data.Data=response.data.Data.data;
            } 
        }
        return response;
    }
    if(response.data.Code === 200){
        return response;
    }else if(response.data.Code === -401){
        //登录失败
        storage.remove('token');
        router.push({path:'/login',query:{redirect:router.currentRoute.value.fullPath}});
        return Promise.reject(response);
    }
   
    else if(response.status=== 401){
        //登录失败
        storage.remove('token');
        router.push({path:'/login',query:{redirect:router.currentRoute.value.fullPath}});
        return response;
        //return Promise.reject(response);
    }else{
        return Promise.reject(response);
    }
},errorHandler)

export default request